package com.example.designpattern;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;
import android.widget.ImageView;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Author 方隽琦
 * Date 2020/12/26
 * Description 图片加载类
 */
public class ImageLoader {


    //图片加载配置对象
    private ImageLoderConfig mConfig;

    //私有化构造函数
    //单例化ImageLoader
    private ImageLoader(){}

    private static ImageLoader mInstance = null;
    //DCL Double Check Lock 模式构造单例
    public static ImageLoader getInstance(){
        if(mInstance == null){
            synchronized (ImageLoader.class){
                if(mInstance == null){
                    mInstance = new ImageLoader();
                }
            }
        }
        return mInstance;
    }



    //初始化ImageLoader
    public void  init(ImageLoderConfig config){
        mConfig = config;
        //检查配置的合法性，内部会根据配置做一些初始化操作
        checkConfig();
    }

    /**
     * 通过ImageLoderConfig 中的配置，来初始化ImageLoader中的成员
     * 这里具体过程省略
     */
    private void checkConfig() {

    }


    //图片内存缓存
    ImageCache mImageCache = new MemoryCache();



    //线程池，线程数量为CPU的数量
    ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //注入缓存实现
    public void setImageCache(ImageCache cache){
        mImageCache = cache;
    }



    public void displayImage(final String url, final ImageView imageView){
        Bitmap bmp = mImageCache.get(url);


        if(bmp !=null){
            imageView.setImageBitmap(bmp);
            return;
        }

        //没有缓存，则提交给线程池进行下载

        submitLoadRequest(url,imageView);

    }

    private void submitLoadRequest(final String url, final ImageView imageView) {




        imageView.setTag(url);
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = downloadImage(url);
                if(bitmap == null){

                    return;
                }
                if(imageView.getTag().equals(url)){
                    imageView.setImageBitmap(bitmap);
                }
                mImageCache.put(url,bitmap);

            }
        });
    }


    private Bitmap downloadImage(String imageUrl) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(imageUrl);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
            conn.disconnect();

        }catch (Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }
}
